package com.tc.netty;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import lombok.extern.slf4j.Slf4j;

import java.net.InetSocketAddress;
import java.util.Scanner;

/**
 * @Auther: tianchao
 * @Date: 2022/2/11 09:40
 * @Description:
 */
@Slf4j
public class CloseFutureClient {
    public static void main(String[] args) throws InterruptedException {
        final NioEventLoopGroup nioEventLoopGroup = new NioEventLoopGroup();
        ChannelFuture channelFuture = new Bootstrap()
                .group(nioEventLoopGroup)
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline().addLast(new LoggingHandler(LogLevel.DEBUG));
                        ch.pipeline().addLast(new StringEncoder());
                    }
                })
                .connect(new InetSocketAddress("localhost", 8083));
        final Channel channel = channelFuture.sync().channel();
        log.debug("{}",channel);
        new Thread(()->{
            final Scanner scanner = new Scanner(System.in);
            while (true){
                log.debug("请输入信息: ");
                final String line = scanner.nextLine();
                if ("q".equals(line)){
                    // 异步操作
                    final ChannelFuture close = channel.close();
                    close.addListener(new ChannelFutureListener() {
                        @Override
                        public void operationComplete(ChannelFuture future) throws Exception {
                            log.debug("处理关闭后的操作");
                            nioEventLoopGroup.shutdownGracefully();
                        }
                    });
                    break;
                }
                channel.writeAndFlush(line);
            }
        }).start();
        //同步
//        final ChannelFuture channelFuture1 = channel.closeFuture();
//        channelFuture1.sync();
//        log.debug("处理关闭后的操作");
    }
}
